package org.rocket.spring.security.demo.web;

import io.swagger.annotations.ApiOperation;
import org.rocket.spring.security.demo.dto.UserDTO;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author He Peng
 * @create 2018-01-21 11:15
 * @update 2018-01-21 11:15
 * @updatedesc : 更新说明
 * @see
 */

@RestController
@RequestMapping(path = "/user")
public class UserController {

    @ApiOperation("查询用户列表")
    @GetMapping(
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE
    )
    public List<UserDTO> getUserList() {
        List<UserDTO> users = new ArrayList<UserDTO>();
        users.add(new UserDTO());
        users.add(new UserDTO());
        users.add(new UserDTO());

        return users;
    }

    @GetMapping(path = "/info")
    public Map<String , Object> getLoginUser(Principal principal) {
        Map<String , Object> loginUserInfo = new HashMap<>(4);
        loginUserInfo.put("username" , principal.getName());
        loginUserInfo.put("class" , principal.getClass());
        return loginUserInfo;
    }

    @PostMapping(
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE ,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE
    )
    public UserDTO create(@Valid @RequestBody UserDTO userDTO , BindingResult errors) {
        if (errors.hasFieldErrors()) {
            errors.getAllErrors().stream().forEach(error -> System.out.println(error));
        }
        return userDTO;
    }
}
